package com.project.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.demo.entity.Praise;
import com.project.demo.service.PraiseService;

import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.*;

/**
 * 点赞：(Praise)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("praise")
public class PraiseController extends BaseController<Praise, PraiseService> {
    /**
     * 服务对象
     */
    @Autowired
    public PraiseController(PraiseService service) {
        setService(service);
    }

    /**
     * 获取点赞趋势统计数据
     * @return 趋势数据（最近7天）
     */
    @GetMapping("trend_statistics")
    public Map<String, Object> getTrendStatistics() {
        try {
            // 查询最近7天的点赞统计数据
            String sql = "SELECT DATE_FORMAT(create_time, '%Y-%m-%d') as date, COUNT(*) as count " +
                    "FROM praise " +
                    "WHERE create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY) " +
                    "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d') " +
                    "ORDER BY date ASC";
            
            Query query = service.runCountSql(sql);
            @SuppressWarnings("unchecked")
            List<Object[]> resultList = query.getResultList();
            
            // 生成最近7天的数据（确保每天都有数据）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            Map<String, Integer> dateMap = new LinkedHashMap<>();
            
            for (int i = 6; i >= 0; i--) {
                cal.setTime(new Date());
                cal.add(Calendar.DAY_OF_MONTH, -i);
                String date = sdf.format(cal.getTime());
                dateMap.put(date, 0);
            }
            
            // 填充查询结果
            for (Object[] row : resultList) {
                String date = (String) row[0];
                Long count = ((Number) row[1]).longValue();
                if (dateMap.containsKey(date)) {
                    dateMap.put(date, count.intValue());
                }
            }
            
            // 转换为前端需要的格式
            List<Map<String, Object>> list = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : dateMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                item.put("date", entry.getKey());
                item.put("count", entry.getValue());
                list.add(item);
            }
            
            JSONObject result = new JSONObject();
            result.put("list", list);
            return success(result);
        } catch (Exception e) {
            log.error("获取点赞趋势统计数据失败", e);
            return error(50000, "获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取点赞状态分布统计数据
     * @return 状态分布数据（已点赞、已取消）
     */
    @GetMapping("status_statistics")
    public Map<String, Object> getStatusStatistics() {
        try {
            // 查询已点赞数量
            String likedSql = "SELECT COUNT(*) FROM praise WHERE status = 1";
            Query likedQuery = service.runCountSql(likedSql);
            Object likedObj = likedQuery.getSingleResult();
            Long liked = likedObj != null ? ((Number) likedObj).longValue() : 0L;
            
            // 查询已取消数量
            String cancelledSql = "SELECT COUNT(*) FROM praise WHERE status = 0";
            Query cancelledQuery = service.runCountSql(cancelledSql);
            Object cancelledObj = cancelledQuery.getSingleResult();
            Long cancelled = cancelledObj != null ? ((Number) cancelledObj).longValue() : 0L;
            
            // 转换为前端需要的格式
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> likedItem = new HashMap<>();
            likedItem.put("name", "已点赞");
            likedItem.put("value", liked.intValue());
            list.add(likedItem);
            
            Map<String, Object> cancelledItem = new HashMap<>();
            cancelledItem.put("name", "已取消");
            cancelledItem.put("value", cancelled.intValue());
            list.add(cancelledItem);
            
            JSONObject result = new JSONObject();
            result.put("list", list);
            return success(result);
        } catch (Exception e) {
            log.error("获取点赞状态分布统计数据失败", e);
            return error(50000, "获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取内容点赞排行榜
     * @return 排行榜数据
     */
    @GetMapping("ranking")
    public Map<String, Object> getRanking() {
        try {
            // 查询内容点赞排行榜（按内容分组统计点赞数，只统计已点赞的）
            String sql = "SELECT source_table, source_id, COUNT(*) as count " +
                    "FROM praise " +
                    "WHERE status = 1 " +
                    "GROUP BY source_table, source_id " +
                    "ORDER BY count DESC " +
                    "LIMIT 10";
            
            Query query = service.runCountSql(sql);
            @SuppressWarnings("unchecked")
            List<Object[]> resultList = query.getResultList();
            
            // 转换为前端需要的格式
            List<Map<String, Object>> list = new ArrayList<>();
            for (Object[] row : resultList) {
                Map<String, Object> item = new HashMap<>();
                item.put("source_table", row[0]);
                item.put("source_id", row[1]);
                item.put("count", ((Number) row[2]).intValue());
                list.add(item);
            }
            
            JSONObject result = new JSONObject();
            result.put("list", list);
            return success(result);
        } catch (Exception e) {
            log.error("获取内容点赞排行榜失败", e);
            return error(50000, "获取排行榜数据失败: " + e.getMessage());
        }
    }

}


